package com.jaws.core.mvc.filter;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

import org.apache.commons.io.IOUtils;

import com.google.common.base.Charsets;

/**
 * http包装，主要是防止流只能读取一次
 * @author maojian
 * @date 2018-07-05 10:55:16
 * @since v1.0.0
 */
public class CacheHttpServletRequestWrapper extends HttpServletRequestWrapper {

	private final byte[] body;

	final ByteArrayInputStream bais;

	public CacheHttpServletRequestWrapper(HttpServletRequest request) throws IOException {
		super(request);
		body = IOUtils.toByteArray(request.getInputStream());
		bais = new ByteArrayInputStream(body);
	}

	@Override
	public BufferedReader getReader() throws IOException {
		return new BufferedReader(new InputStreamReader(getInputStream()));
	}

	public String getBodyContent() {
		return new String(body, Charsets.UTF_8);
	}

	@Override
	public ServletInputStream getInputStream() throws IOException {
		return new ServletInputStream() {

			@Override
			public int read() throws IOException {
				return bais.read();
			}

			@Override
			public boolean isFinished() {
				// TODO Auto-generated method stub
				return false;
			}

			@Override
			public boolean isReady() {
				// TODO Auto-generated method stub
				return false;
			}

			@Override
			public void setReadListener(ReadListener readListener) {
				// TODO Auto-generated method stub

			}
		};
	}

}